<template>
    <div >
        <el-header style="height: auto" class="top">
                <el-row type="flex" justify="space-between">
                    <el-col :span="6" class="query-col-right" v-show="investigationShow">
                        <el-form :inline="true">
                            <el-form-item style="display: inline;float: left">
                                <el-upload
                                    ref="upload"
                                    action="/activityConsole/activityMessage/importXls"
                                    accept=".xls,.xlsx"
                                    :limit="1"
                                    :multiple="false"
                                    :file-list="fileList"
                                    :on-change="fileChange"
                                    :on-remove="fileChange"
                                    :data="activityId"
                                    :on-success="fileUploadSuccess"
                                    :on-error="fileUploadError"
                                    :auto-upload="false">
                                    <el-button slot="trigger" size="medium" type="primary"
                                               v-show="uploadShow">导入
                                    </el-button>
                                    <el-button v-show="!uploadShow" style="margin-left: 10px;" size="medium"
                                               type="success" @click="submitUpload">开始导入
                                    </el-button>
                                </el-upload>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </el-header>
            <el-button type="primary" class="btn" @click=addquestionnaire>添加答题</el-button>
            <el-button type="primary" class="btn" @click="Publish">保存发布</el-button>
        <div class="container">
            <div class="content" v-for="(domain, index) in questionnaireMessage" :key="index">
                <!-- 左部分 -->
                <div class="left">
                    <el-form :model="domain" ref="domain" label-width="100px">
                        <el-form-item label="题目必答">
                            <el-switch v-model="domain.mustAnswer" class="switch"></el-switch>
                        </el-form-item>
                        <el-form-item label="选项随机">
                            <el-switch v-model="domain.isRandom" class="switch"></el-switch>
                        </el-form-item>
                        <el-form-item label="是否多选">
                            <el-switch v-model="domain.isSingle" class="switch"></el-switch>
                        </el-form-item>
                    </el-form>
                </div>
                <!-- 右部分 -->
                <div class="right">
                    <el-form :model="domain" ref="domain" label-width="100px" class="demo-ruleForm" :rules="msgInfoRules">
                        <el-form-item label="标题:" class="header" prop="questionnaireName">
                            <el-input v-model="domain.questionnaireName"></el-input>
                        </el-form-item>
                        <div class="nav">
                            <el-form-item label="选项1:" v-for="(domai, index) in domain.optionMessageList"
                                        :label="'选项' + Number( index + 1)"
                                        :key="index"
                                        :rules="[
                                                {required: true, message: '请输入选项', trigger: 'blur'}
                                                ]"
                                        :prop="'optionMessageList.' + index + '.optionName'">
                                <el-input v-model="domai.optionName" class="one"
                                ></el-input>
                                <el-checkbox v-model="domai.correctAnswer">正确答案</el-checkbox>
                                <el-button type="primary" size="small" @click.prevent="removeDomain(domai, domai.key)">删除
                                </el-button>
                            </el-form-item>
                        </div>
                        <i class="el-icon-delete" @click="deleteItem(index)"></i>
                        <el-button type="primary" class="btn1" @click="addDomain(domain.optionMessageList)">添加选项</el-button>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    import request from '@/utils/request';
    export default {
        name: 'edit',
        props: ['json'],
        data() {
            return {
            	investigationShow:true,
                uploadShow: true,
                fileList: [],
                activityId: {"activityId":""},
                questionnaireMessage: [{
                    questionnaireName: '',
                    mustAnswer: false,
                    isRandom: false,
                    isSingle: false,
                    optionMessageList: [{
                        optionName: '',
                        correctAnswer: 0,
                    }]
                }],
                msgInfoRules: {
                    questionnaireName: [
                        {required: true, trigger: 'blur', message: '请输入问卷标题'}
                    ]
                }
            }
        },
        mounted() {
        	console.log('nihao dasjdgash')
            console.log(this.json.templateMark)
            if(this.json.templateMark === 'investigation') {
            	this.investigationShow = false
            }
            this.$nextTick(function () {
                this.activityId.activityId = this.json.activityId
                if (this.json.activityId != undefined && this.json.pageModel == 'condtion' && this.json.templateMark !='daily') {
                    this.getInfo();
                }
                
            });
        },
        methods: {
            // 回显数据
            getInfo() {
                //////获取编辑信息
                const _this = this;
                _this.axios.get('/activityConsole/activityMessage/getQuestionnaireMessage?activityId=' + _this.json.activityId, {
                    headers: {
                        'Content-Type': 'application/json;charset=utf-8'
                    }
                })
                    .then(function (res) {
                        let dateObj = res.data.data;
                        console.log(dateObj)
                        if (dateObj.length) {
                            for (let i in dateObj) {
                                let date = dateObj[i]
                                 date.isSingle = date.isSingle == 1 ? true : false;
                                 date.mustAnswer = date.mustAnswer == 1 ? true : false;
                                 date.isRandom = date.isRandom == 1 ? true : false;
                                 console.log(date.isSingle)
                                for (let j in date.optionMessageList) {
                                    console.log(dateObj[i].optionMessageList[j].correctAnswer);
                                    dateObj[i].optionMessageList[j].correctAnswer = dateObj[i].optionMessageList[j].correctAnswer == 1 ? true : false;
                                }
                                _this.questionnaireMessage = dateObj;
                            }
                            // 回显 isSinge按钮
                        }
                    }).catch(function (error) {
                    console.log(error);
                }).then(function () {
                });
            },
            // // 添加选项
            addDomain(data) {
                let obj = {
                    optionName: '',
                    correctAnswer: 0,
                };
                data.push(obj);
            },
            // // 删除选项
            removeDomain(domai, key) {
                let ques = this.questionnaireMessage
                for (let i = 0; i < ques.length; i++) {
                    // ques[i]是在questionnaire这一层
                    let doma = ques[i].optionMessageList
                    let index = doma.indexOf(domai)
                    if (index !== -1) {
                        doma.splice(index, 1)
                    }
                }
            },
            // // 添加问卷
            addquestionnaire() {
                let ques = this.questionnaireMessage;
                ques.push({
                    questionnaireName: '',
                    mustAnswer: 0,
                    isRandom: 0,
                    isSingle: 0,
                    optionMessageList: [{
                        optionName: '',
                        correctAnswer: 0,
                    }]
                })
            },
            // // 删除每一项
            deleteItem(index) {
                let ques = this.questionnaireMessage;
                if (ques.length == 1) {
                    return false;
                } else {
                    ques.splice(index, 1);
                }
                console.log(ques)
            },
            //发布
            Publish() {
                let that = this;
                 let params = JSON.parse(JSON.stringify(that.questionnaireMessage));
                // let params = that.questionnaireMessage

                for (let i in params) {
                    let data = params[i];
                    console.log(data.isSingle)
                    data.isSingle= data.isSingle == true ? 1 : 0;
                    data.mustAnswer= data.mustAnswer == true ? 1 : 0;
                    data.isRandom= data.isRandom == true ? 1 : 0;
                    //標題不能爲空
                    if (data.questionnaireName == '') {
                        that.$message({
                            type: 'error',
                            message: "标题必选"
                        });
                        return
                    }
                    // 单选模式，勾选1个正确答案
                    if (data.isSingle == 0) {

                        let idx = 0;
                        data.optionMessageList.forEach(item => {
                            if (item.correctAnswer == 1) {
                                idx++
                            }
                        })
                        if (idx > 1) {
                            this.$message({
                                type: 'error',
                                message: "单选模式，如想添加多个正确答案，请点击左侧多选按钮"
                            });
                            return;
                        }
                    }
                    console.log(this.json.templateMark)

                    //多选模式，能勾选多个正确答案
                    if(data.isSingle == 1){

                        let one = 0;
                        data.optionMessageList.forEach(item => {
                            if(item.correctAnswer == 1 ){
                                one++
                            }
                        })
                        console.log('啊啊啊')
                        console.log(one)
                        if (one == 1) {
                            this.$message({
                                type: 'error',
                                message: "多选模式，请勾选多个答案"
                            });
                            return;
                        }
                    }
                    //判断选项是否为空
                    if (data.optionMessageList.length !== 0) {
                        //有选项的时候，选项不能为空
                        for (let j in data.optionMessageList) {
                            let date = data.optionMessageList[j];
                            if (date.optionName == '') {
                                that.$message({
                                    type: 'error',
                                    message: "选项不能为空"
                                });
                                return;
                            }
                        }
                        // 正确选项
                        let flag = true;
                        if(this.json.templateMark === 'investigation') {
                    		flag = false
                    	}else {
	                        for (let j = 0; j < data.optionMessageList.length; j++) {
                            console.log(data.optionMessageList[j].correctAnswer);
                            if (data.optionMessageList[j].correctAnswer) {
                                flag = false;
                            }
                        }
                    	}

                        if (flag) {
                            that.$message({
                                type: 'error',
                                message: "缺少正确选项"
                            });
                            return;
                        }
                        //correctAnswer把本地的true false改为1， 0
                        for (let j = 0; j < data.optionMessageList.length; j++) {
                            if (data.optionMessageList[j].correctAnswer) {
                                data.optionMessageList[j].correctAnswer = 1;
                            } else {
                                data.optionMessageList[j].correctAnswer = 0;
                            }
                        }
                    //    把本地的是否多选true false改为1， 0
                    }
                }
                this.axios.post('/activityConsole/activityMessage/addQuestionnaireMessage/' + that.json.activityId, params, {
                    headers: {
                        'Content-Type': 'application/json;charset=utf-8'
                    }
                })
                    .then(function (res) {
                        let state = res.status == 200 ? 'success' : 'error';
                        that.getInfo();
                        that.$message({
                            type: state,
                            message: "success"
                        });
                    }).catch(function (error) {
                    console.log(error);
                })
                    .then(function () {
                    });
            },
            importXls() {
                let ques = this.questionnaireMessage;
            },
            submitUpload() {
                console.log("%c--submitUpload--", "color:#4b4");
                this.$refs['upload'].submit();
            },
            fileChange(file, fileList) {
                console.log("%c--fileChange--", "color:#4b4");
                console.log(fileList);
                console.log(this.fileList);
                this.uploadShow = fileList.length == 0;
            },
            fileUploadSuccess(response, file, fileList) {
                console.log("%c--fileUploadSuccess--", "color:#4b4");
                console.log(response,file,fileList);
                if (response.status == 200) {
                    this.$refs['upload'].clearFiles();
                    this.$message({
                        type: 'success',
                        message: response.description
                    });
                } else {
                    this.$message({
                        type: 'error',
                        message: response.description,
                    });
                }
            },
            fileUploadError(err) {
                console.log(err);
                this.$message({
                    type: 'error',
                    message: '导入失败',
                });
            },
        },
    }
</script>
<style scoped>
    .container {
        width: 100%;
        height: 100%;
    }
    .content {
        width: 100%;
        height: auto;
        margin: 0 auto;
        display: flex;
    }
    .left {
        flex: 1;
        padding: 50px 0 0 0;
    }
    .right {
        flex: 5;
        padding-top: 20px;
        overflow-y: auto;
    }
    .demo-ruleForm {
        width: 100%;
        height: auto;
        border: 2px solid #eee;
        border-radius: 10px;
        position: relative;
        margin-bottom: 10px;
    }
    .header {
        height: 70px;
        border-bottom: 2px solid #000;
        padding-top: 10px;
        border-bottom: 2px solid #eee;
        border-radius: 10px 10px 0 0;
    }
    .el-input {
        width: 200px;
        padding-top: 0px;
        height: 30px;
        float: left;
    }
    .nav {
        overflow-y: auto;
    }
    .btn {
        position: fixed;
        top: 30%;
        right: 80px;
        width: 150px;
        margin-bottom: 10px;
        float: right;
    }
    .btn:nth-child(2) {
        top: 35%;
    }
    .btn1 {
        display: block;
        margin: 10px auto;
        width: 150px;
    }
    .el-icon-delete {
        cursor: pointer;
        width: 30px;
        height: 50px;
        position: absolute;
        right: 18px;
        top: 50%;
    }
    .one {
        margin-right: 15px;
    }
</style>
